/*
 * Copyright 2019-2029 geekidea(https://github.com/geekidea)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.app.brilliant.common.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.app.brilliant.common.vo.PageContainer;
import com.app.brilliant.util.PageUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author geekidea
 * @date 2018-11-08
 */
public interface BaseService<T> extends IService<T> {

    /**
     * 分页并按时间倒序排序
     */
    default PageContainer<T> page(Map<String, Object> param) {
        Page<T> page = PageUtils.getPage(param);
        //设置默认排序(创建时间倒序)
        page.setOrders(Collections.singletonList(OrderItem.desc("create_time")));
        //默认分页
        return PageContainer.of(this.page(page));
    }

    default PageContainer<T> page(Map<String, Object> param, List<OrderItem> orders) {
        Page<T> page = PageUtils.getPage(param);
        //设置默认排序(创建时间倒序)
        page.setOrders(orders);
        //默认分页
        return PageContainer.of(this.page(page));
    }

    default boolean sort(Integer sort, String sortColumn) {
        UpdateWrapper<T> updateWrapper = new UpdateWrapper<>();
        updateWrapper.setSql(StrUtil.format("{} = {} + 1", sortColumn, sortColumn));
        updateWrapper.ge(sortColumn, sort);
        return this.update(updateWrapper);
    }

    default boolean sort(Integer sortNew, Integer sortOld, String sortColumn) {
        UpdateWrapper<T> updateWrapper = new UpdateWrapper<>();
        if (sortOld == 0) {
            return sort(sortNew, sortColumn);
        }
        if (sortNew > sortOld) {
            updateWrapper.setSql(StrUtil.format("{} = {} - 1", sortColumn, sortColumn));
            updateWrapper.gt(sortColumn, sortOld);
            updateWrapper.le(sortColumn, sortNew);
        }else {
            updateWrapper.setSql(StrUtil.format("{} = {} + 1", sortColumn, sortColumn));
            updateWrapper.ge(sortColumn, sortNew);
            updateWrapper.lt(sortColumn, sortOld);
        }
        return this.update(updateWrapper);
    }

}
